package com.edais.actions;

import com.edais.domain.ErrorMessageSetting;
import com.edais.domain.ExtractConfig;
import com.edais.domain.UserExtractInfo;
import com.edais.domain.gift.PointGrade;
import com.edais.service.*;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.JsonUtil;
import com.edais.util.Message;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/withdrawals")

public class WithdrawsCashAction implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static final Log logger = LogFactory.getLog(WithdrawsCashAction.class);

	@Autowired
	private WithdrawsCashService withdrawsCashService;

	@Autowired
	private UserService userService;

	@Autowired
	private OptionService optionsService;

	@Autowired
	private UserCardService userCardService;

	@Autowired
	private RateRisesCouponsService rateRisesCouponsService;

	@Autowired
	private ErrorMessageService errorMessageService;

	@Autowired
	private ThirdProductRouteService thirdProductRouteService;

	@Autowired
	private SMSService sMSService;

	@Autowired
	private UserExtractInfoService userExtractInfoService;

	/**
	 * 申请提现
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/withdrawal")
	public void initWithdrawal(HttpServletRequest request, HttpServletResponse response) {

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId"); // 用户id

		// 用户id为空
		if (StringUtils.isBlank(userId)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001, Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			logger.info("/withdrawals/withdrawal 传入参数为空-----userId");
			return;
		}

		try {
			String transCode = "E300012";
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("userId", userId);
			String jsonStr = CommonUtil.constructJsonStr(transCode, userId, paramMap);

			// 获取提现所需的基本要素（可提现金额，提现手续费（单笔收费），提现手续费（费率）,手机号或者邮箱）
			Map<String, Object> jsonMap = withdrawsCashService.getWithdrawsCashItem(jsonStr, userId);
			boolean needProvinceAndCity = this.optionsService.withdrawNeedProvinceAndCity(userId);
			jsonMap.put("needProvinceAndCity", needProvinceAndCity);
			String result = JsonUtil.getJsonStringFromMap(jsonMap);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;

		} catch (Exception e) {
			logger.info("/withdrawals/initWithdrawal 申请提现 异常：" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001, Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			return;
		}
	}

	/**
	 * 查询提现最终确认方法
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/queryFinalWithdrawlInfo")
	public void queryFinalWithdrawlInfo(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId"); // 用户id
		String extractMoney = paramsMap.get("extractMoney"); // 提现金额
		String withdrawFlag = paramsMap.get("withdrawFlag"); // 提现标识 ZSHTPAY

		if (StringUtils.isBlank(userId)) {
			logger.info("userId为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001, Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			return;
		}
		if (StringUtils.isBlank(extractMoney)) {
			logger.info("extractMoney为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001, Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			return;
		}
		try {
			// 查询用户等级信息
			PointGrade userPg = userExtractInfoService.queryPointGradeByUserId(userId);
			// 查询等级提现相关信息
			ExtractConfig userEc = userExtractInfoService.queryExtractConfigByPointGrade(userPg.getGrade());

			// 查询下一个工作日提示信息
			String nextWorkingDay = "";

			Date currentDate = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			// 提现金额
			BigDecimal extractAmount = new BigDecimal(extractMoney);
			// 提现手续费
			BigDecimal extractFee = BigDecimal.ZERO;
			// 提现到账金额
			BigDecimal realAmount = BigDecimal.ZERO;
			// 提现手续费率
			BigDecimal extractFeeRate = BigDecimal.ZERO;
			Map<String, Object> resultMap = new HashMap<String, Object>();
			SimpleDateFormat extractDaySdf = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat extractMonthSdf = new SimpleDateFormat("yyyy-MM");
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("userId", userId);
			UserExtractInfo userExctractInfo = userExtractInfoService.getUserExtractInfo(param);
			if (userExctractInfo == null) {
				userExctractInfo = new UserExtractInfo();
				userExctractInfo.setUserId(Integer.parseInt(userId));
				userExctractInfo.setUserName(userId);
				userExctractInfo.setExtractDay(extractDaySdf.format(new Date()));
				userExctractInfo.setExtractMonth(extractMonthSdf.format(new Date()));
				userExctractInfo.setExtractNormalMonthNumber(0);
				userExctractInfo.setExtractNormalMonthAmount(BigDecimal.ZERO);
				userExctractInfo.setExtractQuickDayNumber(0);
				userExctractInfo.setExtractQuickDayAmount(BigDecimal.ZERO);
			}
			if (!"ZSHTPAY".equals(withdrawFlag)) {
				nextWorkingDay = this.userCardService.queryNextWorkingDay(sdf.format(currentDate));
				if ((new SimpleDateFormat("yyyy-MM")).format(new Date()).equals(userExctractInfo.getExtractMonth())
						&& userExctractInfo.getExtractNormalMonthNumber() >= userEc.getNormalMonthNumber()) {
					extractFeeRate = userEc.getNormalFeeFate();
					extractFee = extractAmount.multiply(extractFeeRate).setScale(2, RoundingMode.UP);
					realAmount = realAmount.subtract(extractFee);
					if (BigDecimal.ZERO.compareTo(realAmount) >= 0) {
						resultMap = errorMessageService.getErrorMessage("EXTRACT_ARRIVED_AMOUNT_IS_ZERO");
						resultMap.put("rescode", Consts.ERROR_CODE);
						resultMap.put("resmsg", Consts.ErrorMsg.MSG00001);
						resultMap.put("resmsg_cn", getErrorMessage(resultMap));
						String result = JsonUtil.getJsonStringFromMap(resultMap);
						CommonUtil.responseJson(result, response);
					}
				}
			} else {
				if (extractAmount.compareTo(userEc.getQuickSingleAmount()) > 0) {
					resultMap = errorMessageService.getErrorMessage("EXCEED_QUICK_SINGLE_AMOUNT");
					resultMap.put("rescode", Consts.ERROR_CODE);
					resultMap.put("resmsg", Consts.ErrorMsg.MSG00001);
					resultMap.put("resmsg_cn", getErrorMessage(resultMap));
					String result = JsonUtil.getJsonStringFromMap(resultMap);
					CommonUtil.responseJson(result, response);
				}
				if (extractDaySdf.format(new Date()).equals(userExctractInfo.getExtractDay())) {
					if (userExctractInfo.getExtractQuickDayAmount().add(extractAmount).compareTo(userEc.getQuickDayAmount()) > 0) {
						resultMap = errorMessageService.getErrorMessage("EXCEED_QUICK_DAY_AMOUNT");
						resultMap.put("rescode", Consts.ERROR_CODE);
						resultMap.put("resmsg", Consts.ErrorMsg.MSG00001);
						resultMap.put("resmsg_cn", getErrorMessage(resultMap));
						String result = JsonUtil.getJsonStringFromMap(resultMap);
						CommonUtil.responseJson(result, response);
						return;
					}
					if (userExctractInfo.getExtractQuickDayNumber().compareTo(userEc.getQuickDayNumber()) >= 0) {
						resultMap = errorMessageService.getErrorMessage("EXCEED_QUICK_DAY_NUMBER");
						resultMap.put("rescode", Consts.ERROR_CODE);
						resultMap.put("resmsg", Consts.ErrorMsg.MSG00001);
						resultMap.put("resmsg_cn", getErrorMessage(resultMap));
						String result = JsonUtil.getJsonStringFromMap(resultMap);
						CommonUtil.responseJson(result, response);
						return;
					}
				}
			}
			// 提现到账提示信息
			String promptInfo = "";
			if (StringUtils.isNotBlank(nextWorkingDay)) {
				promptInfo = "预计到账时间：" + nextWorkingDay;
			} else {
				nextWorkingDay = sdf.format(currentDate);
				promptInfo = "预计两小时内到账";
			}

			jsonMap.put("promptInfo", promptInfo);
			jsonMap.put("nextWorkingDay", nextWorkingDay);
			jsonMap.put("extractFee", extractFee.toString());
			jsonMap.put("extractFeeRate", extractFeeRate.toString());
			jsonMap.put("userVipGrade", userEc.getPointGrade());
			jsonMap.put("realAmount", realAmount.toString());

			String result = CommonUtil.setResultStringCn(jsonMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("withdrawals/queryFinalWithdrawlInfo 异常:", e);
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
					Consts.ErrorMsg.MSG00001, Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}

	}

	/**
	 * 获取返回的信息
	 * 
	 * @param errorMessageMap
	 * @return
	 */
	public String getErrorMessage(Map<String, Object> errorMessageMap) {
		ErrorMessageSetting ems = (ErrorMessageSetting) errorMessageMap.get("errorMessage");
		String messageContent = ems.getMessage_content();
		return messageContent;
	}

	/**
	 * 查询提现申请信息
	 */
	@RequestMapping(value = "/queryExtractCashFront")
	public void queryExtractCashFront(HttpServletRequest request, HttpServletResponse response) {

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String reqId = paramsMap.get("reqId");// 第三方上送订单号

		reqId = "LBPay20151112144728863112822278";
		String logInfo = "withdrawals/queryExtractCashFront:查询提现申请详情_reqId="+reqId;

		if (StringUtils.isBlank(reqId)) {
			logger.error(logInfo+"查询失败:参数为空");
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			return;
		}

		try {

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("reqId", reqId);

			Map<String, Object> jsonMap = userExtractInfoService.queryExtractCashFront(logInfo,map);
			// 处理返回结果
			String result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJson(result, response);

		} catch (Exception e) {
			logger.error("withdrawals/queryExtractCashFront 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}

}
